//
//  AppState.swift
//  aishop
//
//  Created by tuguowei on 2025/10/21.
//

import SwiftUI
import Combine

// 定义应用导航目标
enum NavigationDestination {
    case userInfo
    case userIntegral
    case userMoney
    case userSign
    case userCollection
    case userAddress
    case userSpread
    case userSettled
    case userGrade
    case userCoupon
    case couponList
}

class AppState: ObservableObject {
    @Published var isLoggedIn: Bool = false
    @Published var userInfo: UserInfo?
    @Published var currentNavigation: NavigationDestination?
    
    init() {
        // 从UserDefaults中加载token判断登录状态
        self.isLoggedIn = UserDefaults.standard.string(forKey: APIConfig.tokenName) != nil
        loadUserInfo()
    }
    
    private func loadUserInfo() {
        if isLoggedIn {
            if let userData = UserDefaults.standard.data(forKey: "userInfo"),
               let decodedUser = try? JSONDecoder().decode(UserInfo.self, from: userData) {
                self.userInfo = decodedUser
            }
        }
    }
    
    func navigate(to destination: NavigationDestination) {
        // 只有登录状态才能导航
        if isLoggedIn {
            self.currentNavigation = destination
        }
    }
    
    func logout() {
        self.userInfo = nil
        self.isLoggedIn = false
        UserDefaults.standard.set(false, forKey: APIConfig.tokenName)
        UserDefaults.standard.removeObject(forKey: "userInfo")
    }
}